import React, { useCallback, useRef, useState } from 'react'
import { Layout,Button,ColorPicker,Col, InputNumber, Row, Slider, Input,  } from 'antd';
import { BankOutlined, BarsOutlined, CloudOutlined, CopyrightOutlined, CrownOutlined, DeleteOutlined, DownOutlined, FileAddOutlined, FolderOutlined, FormatPainterOutlined, RotateLeftOutlined, RotateRightOutlined } from '@ant-design/icons';
import type { InputNumberProps } from 'antd';
import 'react-image-crop/dist/ReactCrop.css';
import html2canvas from 'html2canvas';
import './index.css'

// 引入组件
import Sidebar from '../../components/Sidebar/Sidebar';
import CommentDrawer from '../../components/CommentDrawer/CommentDrawer';
import ShareButton from '../../components/ShareButton/ShareButton';

const { Header,Content } = Layout;

const CropComponent = ({ image, onCropChange }) => {
  const handleWidthChange = (e) => {
    onCropChange({ ...image.crop, width: parseInt(e.target.value) });
  };

  const handleHeightChange = (e) => {
    onCropChange({ ...image.crop, height: parseInt(e.target.value) });
  };

  return (
    <div>
      <input
        type="number"
        value={image.crop?.width || 100}
        onChange={handleWidthChange}
        placeholder="宽度"
      />
      <input
        type="number"
        value={image.crop?.height || 100}
        onChange={handleHeightChange}
        placeholder="高度"
      />
    </div>
  );
};

const Index:React.FC = () => {
  const [inputValue, setInputValue] = useState(1);
  const onChange: InputNumberProps['onChange'] = (newValue) => {
    setInputValue(newValue as number);
  };
  const [selectedImageIndex, setSelectedImageIndex] = useState(null);
  const [newWidth, setNewWidth] = useState(100);
  const [newHeight, setNewHeight] = useState(100);
  const handleResizeClick = () => {
    if (selectedImageIndex !== null) {
      const updatedImages = [...images];
      updatedImages[selectedImageIndex].crop.width = newWidth;
      updatedImages[selectedImageIndex].crop.height = newHeight;
      setImages(updatedImages);
    }
  };

const [images, setImages] = useState([]);
const [backgroundImage, setBackgroundImage] = useState(''); // 状态变量存储背景图
const [watermarkAdded, setWatermarkAdded] = useState(false); // 水印状态

  const handleDrop = (e) => {
    e.preventDefault();
    const src = e.dataTransfer.getData('text/plain');
    const newImage = {
      id: Date.now(),
      src: src,
      left: e.clientX - e.currentTarget.getBoundingClientRect().left,
      top: e.clientY - e.currentTarget.getBoundingClientRect().top,
      crop: { width: 100, height: 100 },
      hasText: src.includes('<p>'), // 这里可以用更复杂的逻辑判断是否含有 <p>
      text: src.includes('<p>') ? '输入的文本' : '', // 示例文本
      style: { fontSize: '16px', color: '#000' }
    };
    setImages((prev) => [...prev, newImage]);
  };

   const handleTextChange = (index, newText) => {
    const updatedImages = [...images];
    updatedImages[index].text = newText;
    setImages(updatedImages);
  };

  const handleDragEnd = (index, e) => {
    const updatedImages = [...images];
    const boundingRect = e.currentTarget.parentNode.getBoundingClientRect();
    const newLeft = e.clientX - boundingRect.left;
    const newTop = e.clientY - boundingRect.top;

    updatedImages[index].left = newLeft; 
    updatedImages[index].top = newTop;

    setImages(updatedImages);
  };   
  
  const handleUploadClick = () => {
    const newBackgroundImage = prompt("请输入背景图的 URL");
    if (newBackgroundImage) {
      setBackgroundImage(newBackgroundImage);
    }
  }; 

const handleCutout = useCallback(async () => {
  if (selectedImageIndex !== null) {
    const selectedImage = images[selectedImageIndex];

    try {
      const response = await fetch('https://api.remove.bg/v1.0/removebg', {
        method: 'POST',
        headers: {
          'X-Api-Key': 'gf2y6xeSdWGSe4kma7twieNb', // 替换为你的API密钥
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ image_url: selectedImage.src, size: 'auto' })
      });

      if (response.ok) {
        const data = await response.json();
        const updatedImages = [...images];
        updatedImages[selectedImageIndex].src = data.result_url; // 更新为去掉背景后的图片链接
        setImages(updatedImages);
      } else {
        const errorData = await response.json();
        alert(`抠图失败: ${errorData.message}`);
      }
    } catch (error) {
      console.error("请求发生错误:", error);
      alert("请求失败，请重试！");
    }
  } else {
    alert("请先选择一张图片进行抠图");
  }
}, [selectedImageIndex, images]);

   const handleDelete = () => {
    if (selectedImageIndex !== null) {
      const updatedImages = images.filter((_, index) => index !== selectedImageIndex);
      setImages(updatedImages);
      setSelectedImageIndex(null); // 重置选中状态
    }
  };

  const toggleWatermark = () => {
    setWatermarkAdded((prev) => !prev);
  };

  const downloadImage = () => {
    const element = document.getElementById('zhong-box');
    html2canvas(element).then((canvas) => {
      canvas.toBlob((blob) => {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'download.png'; // 设置下载文件名
        link.click();
      });
    });
  };

  const [width, setWidth] = useState(500);  // 初始宽度
  const [height, setHeight] = useState(600); // 初始高度

  return (
    <Layout style={{ width:'100%',height:'100vh',display:'flex',flexDirection:'column' }}>
      <Header style={{ height:'50px',color:'#000',borderBottom:'1px solid #eee' }}>
        <div style={{ display:'flex',alignItems:'center' }}>
        <p style={{ marginLeft:'-40px' }}><BankOutlined /></p>
        <p style={{ margin:'0px 10px' }}>文件 <span><DownOutlined /></span></p>
        <div style={{  display:'flex',margin:'0px 10px' }}>
          <p><span><FolderOutlined /></span> 保存至…&nbsp;</p>/
          <p>&nbsp;未命名 <span><DownOutlined /></span></p>
          </div>
        <p style={{ margin:'0px 10px' }}><CloudOutlined /></p>
        <Button style={{ border:'none' }}><RotateLeftOutlined /></Button>
        <Button style={{ border:'none' }}><RotateRightOutlined /></Button>
        </div>
        <div style={{ display:'flex',alignItems:'center' }}>
          <Button style={{ background:'#ff7717',border:'none',color:'#fff' }}><CrownOutlined />加赠<span style={{ color:'#ffcb55' }}>1</span>年</Button>
          <Button style={{ border:'none' }}><CopyrightOutlined /></Button>
          {/* 分享 */}
          <ShareButton />
          <Button type="primary" onClick={downloadImage}>
            <ul style={{ display:'flex',textAlign:'center' }}>
            <li>下载</li>
            <li style={{ borderLeft:'1px solid #fff' }}><BarsOutlined /></li>
          </ul>
          </Button>
        </div>
      </Header>
      <Content style={{ flex:'1',display:'flex',justifyContent:'space-around' }}>
      <div id="zuo">
        <Sidebar></Sidebar>
      </div>
      <div id="zhong">
        <div id='zhong-box' style={{ 
        background: backgroundImage ? `url(${backgroundImage})` : '#fff',
        width:`${width}px`,height:`${height}px`,
        margin:'20px auto',position:'relative',
        overflow: 'hidden',
        border: watermarkAdded ? '2px solid rgba(0, 0, 0, 0.1)' : 'none' // 水印边框样式
         }} 
        onDragOver={(e) => e.preventDefault()}
        onDrop={handleDrop}>
        {watermarkAdded && (
          <div style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%) rotate(-30deg)', // 添加倾斜效果
            opacity: 0.3,
            fontSize: '48px',
            color: 'black',
            pointerEvents: 'none',
            zIndex: 10 // 确保水印位于所有图片的上方 
          }}>
            稿定
          </div>
        )}
        {/* 显示所有拖拽的图片 */}
          {images.map((image, index) => (
      <div
        key={image.id}
        style={{ 
          position: 'absolute', 
          left: image.left, 
          top: image.top, 
          cursor: 'move',
          // cursor: 'pointer',
          zIndex: 1, // 确保图片在水印下方
          // border: selectedImageIndex === index ? '2px solid blue' : 'none'
        }}
        draggable
        onDragEnd={(e) => handleDragEnd(index, e)}
        onClick={() => setSelectedImageIndex(index)}
      >
        {image.hasText ? (  //判断是否有文本内容
              <input
                placeholder="输入文本"
                value={image.text}
                onChange={(e) => handleTextChange(index, e.target.value)}
                style={{ width: '100px', marginTop: '5px' }}
              />
            ) : (
              <img
                src={image.src}
                // alt=""
                alt={`Image ${image.id}`}
                style={{ width: `${image.crop.width}px`, height: `${image.crop.height}px`,cursor: 'pointer',border: selectedImageIndex === index ? '2px solid blue' : 'none' }}
                onClick={() => setSelectedImageIndex(index)}
              />
            )}
        
        {/* 仅在有文本时渲染文本内容 */}
        {image.text && 
          <div style={{ fontSize: image.style.fontSize, color: image.style.color }}>
            <p>{image.text}</p> {/*用 p 标签包裹文本*/}
          </div>
        }
      </div>
    ))}
        </div>
      </div>
      <div id="you">
        {/* 画板/三按钮 */}
        <div style={{ height:'50px',borderBottom:'1px solid #eee' }}>
        <h4 style={{ marginLeft:'10px',marginTop:'5px' }}>画板</h4>
        <ul style={{ display:'flex',marginTop:'5px',marginLeft:'10px' }}>
          <li style={{ marginRight:'10px' }}><FormatPainterOutlined /></li>
          <li style={{ margin:'0px 10px' }}><FileAddOutlined /></li>
          <li style={{ margin:'0px 10px' }}><DeleteOutlined /></li>
        </ul>
        </div>
        {/* 尺寸 */}
        <div style={{ height:'130px',borderBottom:'1px solid #eee',display:'flex',flexDirection:'column' }}>
          <h4 style={{ height:'40px',display:'flex',alignItems:'center',marginLeft:'10px' }}>
            <p style={{ flex:'1' }}>尺寸</p>
            <span style={{ width:'120px',textAlign:'center',color:'#ccc',fontSize:'14px',fontWeight:'normal' }}>
              {/* 1242 x 2208 px */}
              {/* {selectedImageIndex !== null ? `${images[selectedImageIndex].crop.width} x ${images[selectedImageIndex].crop.height} px` : '请选择图像'} */}
              {selectedImageIndex !== null && selectedImageIndex < images.length 
          ? `${images[selectedImageIndex].crop.width} x ${images[selectedImageIndex].crop.height} px` 
          : '请选择图像'}
              </span>
          </h4>
          <div style={{ flex:'1' }}>
          <input
            type="number"
            value={newWidth}
            onChange={(e) => setNewWidth(parseInt(e.target.value))}
            placeholder="新宽度"
          />
          <input
            type="number"
            value={newHeight}
            onChange={(e) => setNewHeight(parseInt(e.target.value))}
            placeholder="新高度"
          />
          <Button onClick={handleResizeClick} style={{marginLeft:'60px',marginRight:'10px',background:'#f1f2f4',marginTop:'10px' }}>调整尺寸</Button>
          <Button style={{background:'#f1f2f4' }} onClick={handleResizeClick}>尺寸延展</Button>
          </div>
        </div>
        {/* 背景图 */}
        <div style={{ height:'80px',borderBottom:'1px solid #eee',display:'flex',flexDirection:'column' }}>
          <h4 style={{ height:'40px',marginLeft:'10px',lineHeight:'40px' }}>背景图</h4>
          <div style={{ flex:'1' }}>
            {/* https://img1.baidu.com/it/u=3263794176,2595089248&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667 */}
            {/* https://img1.baidu.com/it/u=1045034511,106057529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=1083 */}
            {/* https://img2.baidu.com/it/u=2585603829,1437300414&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=1085 */}
            {/* https://img1.baidu.com/it/u=3260181589,3938445&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500 */}
            {/* https://img0.baidu.com/it/u=640642692,1026434131&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=623 */}
          <Button style={{marginLeft:'60px',marginRight:'10px',background:'#f1f2f4' }} onClick={handleUploadClick}>上传图片</Button>
          <Button style={{background:'#f1f2f4',padding:'0px 25px' }} onClick={handleUploadClick}>背景库</Button>
          </div>
        </div>
        {/* 抠图 */}
        <Button style={{margin:'10px',background:'#f1f2f4' }} onClick={handleCutout}>抠图</Button>
        {/* 删除 */}
        <Button style={{margin:'10px',background:'#f1f2f4' }} onClick={handleDelete} 
        disabled={selectedImageIndex === null}>删除</Button>
        {/* 水印 */}
        <Button onClick={toggleWatermark}>{watermarkAdded ? '去除水印' : '添加水印'}</Button>
        {/* 控制 zhong-box 大小的 slider */}
        <>
        <h4 style={{ marginTop:'10px',marginLeft:'10px' }}>调节画布大小</h4>
        <Slider 
        defaultValue={95} 
        disabled={false} 
        onChange={(value) => {
          setWidth(500 * (value / 100)); // 根据滑动条值调整宽度
          setHeight(600 * (value / 100)); // 根据滑动条值调整高度
        }} 
      />
        </>
        {/* 评论功能 */}
        <CommentDrawer />
      </div>
      </Content>
    </Layout>
  )
}

export default Index